import { Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { UserFollowEntity } from '../entity/userFollow';
import { UserInfoEntity } from '../entity/info';

/**
 * 用户关注
 */
@Provide()
export class UserFollowService extends BaseService {
  @InjectEntityModel(UserFollowEntity)
  currentEntity: Repository<UserFollowEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  /**
   *
   * @param userId
   * @param followId
   * @param field countCollects | countFollows | countTeams | countLoves
   * @returns
   */
  async upCount(userId, followId, field, type?:string) {
    console.log('field====>',field);
    
    // 关注
    if (field == 'countFollows') {
      if(parseInt(userId) == parseInt(followId)){
        return '不能关注自己！';
      }else{
        const userInfo = await this.userInfoEntity.findOne({ where: { id: userId } });
        const userFollowInfo = await this.userInfoEntity.findOne({ where: { id: followId } });

        const userFollow = await this.currentEntity.findOne({
          where: { followId: userId, userId: followId },
        });
        const num = userInfo.countFollows*1;
        const numFollow = userFollowInfo.countTeams*1;
    console.log('num====>',num);
    console.log('numFollow====>',numFollow);

        if (userFollow) {
          await this.currentEntity
            .createQueryBuilder()
            .delete()
            .where({ followId: userId, userId: followId })
            .execute();
            // 我的关注着-1
          await this.userInfoEntity
            .createQueryBuilder()
            .update()
            .where({ id: userId })
            .set({ countFollows: num - 1 })
            .execute();
            // 他的粉丝-1
            await this.userInfoEntity
            .createQueryBuilder()
            .update()
            .where({ id: followId })
            .set({ countTeams: numFollow - 1 })
            .execute();
          return 'cancel';
        } else {
          await this.userInfoEntity
            .createQueryBuilder()
            .update()
            .where({ id: userId })
            .set({ [field]: num + 1 })
            .execute();
            await this.userInfoEntity
            .createQueryBuilder()
            .update()
            .where({ id: followId })
            .set({ countTeams: numFollow + 1 })
            .execute();
          await this.currentEntity.save({ followId: userId, userId: followId });
          return 'up';
        }
      }
    } else {
      const userInfo = await this.userInfoEntity.findOne({ where: { id: followId } });
      const num = parseInt(userInfo[field]);
      console.log('num==num=====>',num);

      if (type=='cancel') {
        await this.currentEntity
          .createQueryBuilder()
          .delete()
          .where({ followId: userId, userId: followId })
          .execute();
        await this.userInfoEntity
          .createQueryBuilder()
          .update()
          .where({ id: followId })
          .set({ [field]: num - 1 })
          .execute();
        return 'cancel';
      } else {
        await this.userInfoEntity
          .createQueryBuilder()
          .update()
          .where({ id: followId })
          .set({ [field]: num + 1 })
          .execute();
        await this.currentEntity.save({ followId: userId, userId: followId });
        return 'up';
      }
    }
  }

  /**
   * 是否关注
   */
  async isFollow(userId, followId) {
    const res = await this.currentEntity
      .createQueryBuilder()
      .where({ userId, followId })
      .getOne();

    if (res) {
      return true;
    } else {
      return false;
    }
  }

  async transformInFollow(arr: [any], followId, field = 'userId') {
    if (arr && arr.length) {
      const ids = [];
      arr.map(v => {
        if (v[field]) {
          ids.push(v[field]);
        }
      });

      const set = new Set(ids); //去重复

      const userList = await this.currentEntity
        .createQueryBuilder('a')
        .where('a.id in (:ids)', { ids: [...set] })
        .getMany();

      arr.map((v, k) => {
        arr[k]['user']['is_follow'] = false;
        userList.map(u => {
          if (v[field] == u.userId && u.followId == followId) {
            arr[k]['user']['is_follow'] = true;
          }
        });
      });
    }
    return arr;
  }
}
